<template>
  <div class="task-adjustment">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>
        <i class="bi bi-gear"></i>
        工作任务调整
      </h2>
    </div>

    <!-- 查询表单 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0">
          <i class="bi bi-search"></i> 用户查询
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="searchUser">
          <div class="row">
            <div class="col-md-3">
              <label for="userName" class="form-label">用户名</label>
              <input 
                type="text" 
                class="form-control" 
                id="userName"
                v-model="searchForm.userName"
                placeholder="请输入用户名"
              >
            </div>
            <div class="col-md-3">
              <label for="peopleName" class="form-label">姓名</label>
              <input 
                type="text" 
                class="form-control" 
                id="peopleName"
                v-model="searchForm.peopleName"
                placeholder="请输入姓名"
              >
            </div>
            <div class="col-md-3">
              <label for="userType" class="form-label">用户类型</label>
              <input 
                type="text" 
                class="form-control" 
                id="userType"
                v-model="searchForm.userType"
                placeholder="请输入用户类型"
              >
            </div>
            <div class="col-md-3">
              <label for="partyBranch" class="form-label">党支部</label>
              <input 
                type="text" 
                class="form-control" 
                id="partyBranch"
                v-model="searchForm.partyBranch"
                placeholder="请输入党支部"
              >
            </div>
          </div>
          <div class="row mt-3">
            <div class="col-12">
              <button 
                type="submit" 
                class="btn btn-primary me-2"
                :disabled="loading"
              >
                <i class="bi bi-search"></i>
                <span v-if="loading">查询中...</span>
                <span v-else>查询</span>
              </button>
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="resetSearchForm"
              >
                <i class="bi bi-arrow-clockwise"></i>
                重置
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 查询结果 -->
    <div class="card mb-4" v-if="searchResults.length > 0">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
          <i class="bi bi-list"></i> 查询结果
        </h5>
        <span class="badge bg-primary">共 {{ searchResults.length }} 条记录</span>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th>
                  <input 
                    type="checkbox" 
                    class="form-check-input"
                    @change="selectAll"
                    :checked="allSelected"
                  >
                </th>
                <th>用户ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>身份证号</th>
                <th>手机号</th>
                <th>任务数量</th>
                <th>用户类型</th>
                <th>党支部</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in searchResults" :key="user.id">
                <td>
                  <input 
                    type="checkbox" 
                    class="form-check-input"
                    v-model="user.selected"
                    @change="updateSelection"
                  >
                </td>
                <td>{{ user.id }}</td>
                <td>{{ user.userName }}</td>
                <td>{{ user.peopleName }}</td>
                <td>{{ user.idNo }}</td>
                <td>{{ user.userPhone }}</td>
                <td>{{ user.taskAmount }}</td>
                <td>{{ user.userType }}</td>
                <td>{{ user.partyBranch }}</td>
                <td>
                  <button 
                    class="btn btn-sm btn-outline-primary"
                    @click="addToEditList(user)"
                    :disabled="isInEditList(user.id)"
                  >
                    <i class="bi bi-plus"></i>
                    {{ isInEditList(user.id) ? '已添加' : '添加到编辑列表' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="mt-3" v-if="selectedUsers.length > 0">
          <button 
            class="btn btn-success"
            @click="addSelectedToEditList"
          >
            <i class="bi bi-plus-circle"></i>
            批量添加到编辑列表 ({{ selectedUsers.length }})
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑列表 -->
    <div class="card" v-if="editList.length > 0">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
          <i class="bi bi-pencil-square"></i> 编辑列表
        </h5>
        <div>
          <span class="badge bg-success me-2">{{ editList.length }} 条待编辑</span>
          <button 
            class="btn btn-sm btn-outline-danger"
            @click="clearEditList"
          >
            <i class="bi bi-trash"></i>
            清空列表
          </button>
        </div>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped">
            <thead class="table-secondary">
              <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>任务数量</th>
                <th>用户类型</th>
                <th>党支部</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(user, index) in editList" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.userName }}</td>
                <td>{{ user.peopleName }}</td>
                <td>
                  <input 
                    type="number" 
                    class="form-control form-control-sm"
                    v-model.number="user.taskAmount"
                    min="0"
                  >
                </td>
                <td>
                  <select 
                    class="form-select form-select-sm"
                    v-model="user.userType"
                  >
                    <option value="">请选择用户类型</option>
                    <option 
                      v-for="option in userTypeOptions" 
                      :key="option.value" 
                      :value="option.value"
                    >
                      {{ option.label }}
                    </option>
                  </select>
                </td>
                <td>
                  <select 
                    class="form-select form-select-sm"
                    v-model="user.partyBranch"
                  >
                    <option value="">请选择所属支部</option>
                    <option 
                      v-for="option in partyBranchOptions" 
                      :key="option.value" 
                      :value="option.value"
                    >
                      {{ option.label }}
                    </option>
                  </select>
                </td>
                <td>
                  <button 
                    class="btn btn-sm btn-outline-danger"
                    @click="removeFromEditList(index)"
                  >
                    <i class="bi bi-trash"></i>
                    移除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="mt-3">
          <button 
            class="btn btn-primary me-2"
            @click="batchUpdate"
            :disabled="updating || editList.length === 0"
          >
            <i class="bi bi-save"></i>
            <span v-if="updating">保存中...</span>
            <span v-else>批量保存 ({{ editList.length }})</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 提示信息 -->
    <div v-if="searchResults.length === 0 && !loading && hasSearched" class="alert alert-info">
      <i class="bi bi-info-circle"></i>
      未找到符合条件的用户信息
    </div>
  </div>
</template>

<script>
import api from '@/utils/api'
import { useToast } from '@/composables/useToast'

export default {
  name: 'TaskAdjustment',
  setup() {
    const { showToast } = useToast()
    return { showToast }
  },
  data() {
    return {
      loading: false,
      updating: false,
      hasSearched: false,
      searchForm: {
        userName: '',
        peopleName: '',
        userType: '',
        partyBranch: ''
      },
      searchResults: [],
      editList: [],
      // 字典数据
      userTypeOptions: [],
      partyBranchOptions: []
    }
  },
  computed: {
    selectedUsers() {
      return this.searchResults.filter(user => user.selected)
    },
    allSelected() {
      return this.searchResults.length > 0 && this.searchResults.every(user => user.selected)
    }
  },
  methods: {
    // 获取字典数据
    async loadDictData() {
      try {
        // 获取用户类型字典 (dictId: 9)
        const userTypeResponse = await api.post('/api/Dict/get-by-dict-id', {
          dictId: 9
        })
        if (userTypeResponse.data) {
          this.userTypeOptions = userTypeResponse.data.map(item => ({
            value: item.itemName,
            label: item.itemName,
            itemValue: item.itemValue
          }))
        }

        // 获取所属支部字典 (dictId: 10)
        const partyBranchResponse = await api.post('/api/Dict/get-by-dict-id', {
          dictId: 10
        })
        if (partyBranchResponse.data) {
          this.partyBranchOptions = partyBranchResponse.data.map(item => ({
            value: item.itemName,
            label: item.itemName,
            itemValue: item.itemValue
          }))
        }
      } catch (error) {
        console.error('加载字典数据失败:', error)
        this.showToast('加载字典数据失败: ' + (error.response?.data?.message || error.message), 'error')
      }
    },

    async searchUser() {
      // 检查是否至少填写了一个查询条件
      const hasCondition = Object.values(this.searchForm).some(value => value.trim() !== '')
      if (!hasCondition) {
        this.showToast('请至少填写一个查询条件', 'error')
        return
      }

      this.loading = true
      this.hasSearched = true
      
      try {
        const response = await api.post('/api/UumUser/search', this.searchForm)
        
        if (response.data && response.data.success && Array.isArray(response.data.items)) {
          this.searchResults = response.data.items.map(user => ({
            ...user,
            selected: false
          }))
          
          if (this.searchResults.length === 0) {
            this.showToast('未找到符合条件的用户信息', 'info')
          } else {
            this.showToast(`查询成功，找到 ${this.searchResults.length} 条记录`, 'success')
          }
        } else {
          this.searchResults = []
          this.showToast('查询结果格式异常', 'error')
        }
      } catch (error) {
        console.error('查询用户失败:', error)
        this.searchResults = []
        this.showToast('查询失败: ' + (error.response?.data?.message || error.message), 'error')
      } finally {
        this.loading = false
      }
    },
    
    resetSearchForm() {
      this.searchForm = {
        userName: '',
        peopleName: '',
        userType: '',
        partyBranch: ''
      }
      this.searchResults = []
      this.hasSearched = false
    },
    
    selectAll(event) {
      const checked = event.target.checked
      this.searchResults.forEach(user => {
        user.selected = checked
      })
    },
    
    updateSelection() {
      // 触发计算属性更新
    },
    
    addToEditList(user) {
      if (this.isInEditList(user.id)) {
        this.showToast('该用户已在编辑列表中', 'warning')
        return
      }
      
      this.editList.push({
        id: user.id,
        userName: user.userName,
        peopleName: user.peopleName,
        taskAmount: user.taskAmount,
        userType: user.userType,
        partyBranch: user.partyBranch,
        userPhone: user.userPhone
      })
      
      this.showToast('已添加到编辑列表', 'success')
    },
    
    addSelectedToEditList() {
      let addedCount = 0
      
      this.selectedUsers.forEach(user => {
        if (!this.isInEditList(user.id)) {
          this.editList.push({
            id: user.id,
            userName: user.userName,
            peopleName: user.peopleName,
            taskAmount: user.taskAmount,
            userType: user.userType,
            partyBranch: user.partyBranch,
            userPhone: user.userPhone
          })
          addedCount++
        }
      })
      
      if (addedCount > 0) {
        this.showToast(`已添加 ${addedCount} 个用户到编辑列表`, 'success')
        // 清除选择状态
        this.searchResults.forEach(user => {
          user.selected = false
        })
      } else {
        this.showToast('所选用户已在编辑列表中', 'warning')
      }
    },
    
    isInEditList(userId) {
      return this.editList.some(user => user.id === userId)
    },
    
    removeFromEditList(index) {
      this.editList.splice(index, 1)
      this.showToast('已从编辑列表中移除', 'success')
    },
    
    clearEditList() {
      if (this.editList.length === 0) {
        return
      }
      
      if (confirm('确定要清空编辑列表吗？')) {
        this.editList = []
        this.showToast('编辑列表已清空', 'success')
      }
    },
    
    async batchUpdate() {
      if (this.editList.length === 0) {
        this.showToast('编辑列表为空', 'warning')
        return
      }
      
      if (!confirm(`确定要批量更新 ${this.editList.length} 个用户的信息吗？`)) {
        return
      }
      
      this.updating = true
      let successCount = 0
      let failCount = 0
      
      try {
        for (const user of this.editList) {
          try {
            await api.post('/api/UumUser/update', {
              id: user.id,
              taskAmount: user.taskAmount,
              userType: user.userType,
              partyBranch: user.partyBranch,
              userPhone: user.userPhone
            })
            successCount++
          } catch (error) {
            console.error(`更新用户 ${user.userName} 失败:`, error)
            failCount++
          }
        }
        
        if (successCount > 0) {
          this.showToast(`批量更新完成：成功 ${successCount} 个，失败 ${failCount} 个`, 'success')
          
          if (failCount === 0) {
            // 全部成功，清空编辑列表
            this.editList = []
            // 刷新查询结果
            if (this.hasSearched) {
              await this.searchUser()
            }
          }
        } else {
          this.showToast('批量更新失败', 'error')
        }
      } catch (error) {
        console.error('批量更新异常:', error)
        this.showToast('批量更新异常: ' + error.message, 'error')
      } finally {
        this.updating = false
      }
    }
  },
  mounted() {
    // 组件挂载时加载字典数据
    this.loadDictData()
  }
}
</script>

<style scoped>
.task-adjustment {
  padding: 20px;
}

.form-control-sm {
  font-size: 0.875rem;
}

.table th {
  white-space: nowrap;
}

.table td {
  vertical-align: middle;
}

.badge {
  font-size: 0.75rem;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.alert {
  margin-top: 20px;
}

.card-header h5 {
  margin: 0;
}

.table-responsive {
  max-height: 400px;
  overflow-y: auto;
}
</style>